package com.beordie.controller;

import com.beordie.model.Message;
import com.beordie.model.User;
import com.beordie.mvc.ResponseText;
import com.beordie.mvc.ResponseView;
import com.beordie.service.IUserService;
import com.beordie.service.impl.UserServiceImpl;
import com.beordie.utils.JsonUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Classname AdminController
 * @Description 管理员控制器
 * @Date 2021/7/12 20:14
 * @Created 30500
 */
public class AdminController {
    IUserService userService = new UserServiceImpl();

    @ResponseText("/admin/login.udo")
    public String login(HttpServletRequest request, HttpServletResponse response) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        int remember = Integer.parseInt(request.getParameter("remember"));
        User user = userService.findUser(username, password);
        Message message = new Message();
        if (user != null) {
            message.setStatus(0);
            message.setResult("数据有效");
            request.getSession().setAttribute("username", username);
            Cookie userCookie = new Cookie("username", username);
            // cookie有效时间为 10 Sec
            userCookie.setMaxAge(10 * 60);
            response.addCookie(userCookie);
        } else {
            message.setStatus(-1);
            message.setResult("数据无效");
        }
        return JsonUtils.parseObject(message);
    }

    @ResponseView("/admin/loginOut.udo")
    public String loginOut(HttpServletRequest request, HttpServletResponse response) {
        // session 失效
        request.getSession().removeAttribute("username");
        request.getSession().invalidate();

        return "/login.html";
    }
}
